import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';

import '../../../net/api_service.dart';
import '../../../net/httpsClient.dart';
import '../../../services/utils.dart';
import '../models/comment_entity.dart';
import '../models/delete_comment_entity.dart';
import '../models/delete_post_entity.dart';
import '../models/post_detail_entity.dart';
import '../models/write_comment_entity.dart';

class HomeDetailController extends GetxController {
  // 文章ID
  String postId = '';

  // 响应式数据
  final postDetail = Rxn<PostDetailData>();
  final commentList = <CommentDataList>[].obs;
  final isLoadingDetail = false.obs;
  final isLoadingComments = false.obs;
  final commentTotalCount = 0.obs;

  // 评论输入相关
  final commentController = TextEditingController();
  final isSubmittingComment = false.obs;

  // 删除文章相关
  final isDeletingPost = false.obs;

  // 删除评论状态 - 用于记录正在删除的评论ID
  final deletingCommentIds = <int>{}.obs;

  @override
  void onInit() {
    super.onInit();
    // 获取传递的文章ID
    postId = Get.arguments?['postId']?.toString() ?? '';
    if (postId.isNotEmpty) {
      _loadData();
    } else {
      SmartDialog.showToast('文章ID不能为空');
    }
  }

  // 加载数据
  Future<void> _loadData() async {
    await Future.wait([
      getPostDetail(),
      getComments(),
    ]);
  }

  // 获取文章详情
  Future<void> getPostDetail() async {
    if (postId.isEmpty) return;

    isLoadingDetail.value = true;
    try {
      myLog('获取文章详情，ID: $postId');

      final response =
          await HttpsClient().get('${ApiService.postDetail}?id=$postId');

      if (response == null || response.data == null) {
        SmartDialog.showToast('获取文章详情失败');
        return;
      }

      final entity = PostDetailEntity.fromJson(response.data);
      myLog('文章详情响应: ${response.data}');

      if (entity.code == 100 && entity.data != null) {
        postDetail.value = entity.data;
        myLog('获取文章详情成功: ${entity.data?.title}');
      } else {
        SmartDialog.showToast(entity.message ?? '获取文章详情失败');
      }
    } catch (e, stackTrace) {
      myLog('获取文章详情失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast('获取文章详情失败: $e');
    } finally {
      isLoadingDetail.value = false;
    }
  }

  // 获取评论列表
  Future<void> getComments({
    int pageIndex = 1,
    int pageSize = 10,
    bool isRefresh = false,
  }) async {
    if (postId.isEmpty) return;

    if (!isRefresh) {
      isLoadingComments.value = true;
    }

    try {
      final commentData = {
        "postId": postId,
        "pageIndex": pageIndex,
        "pageSize": pageSize,
      };

      myLog('获取评论列表: $commentData');

      final response =
          await HttpsClient().post(ApiService.comments, data: commentData);

      if (response == null || response.data == null) {
        SmartDialog.showToast('获取评论失败');
        return;
      }

      final entity = CommentEntity.fromJson(response.data);
      myLog('评论响应: ${response.data}');

      if (entity.code == 100 && entity.data != null) {
        if (isRefresh || pageIndex == 1) {
          // 刷新或第一页，替换数据
          commentList.value = entity.data!.list ?? [];
        } else {
          // 加载更多，追加数据
          commentList.addAll(entity.data!.list ?? []);
        }
        commentTotalCount.value = entity.data!.totalCount ?? 0;

        myLog('获取评论成功，共 ${commentList.length} 条');
      } else {
        SmartDialog.showToast(entity.message ?? '获取评论失败');
      }
    } catch (e, stackTrace) {
      myLog('获取评论失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast('获取评论失败: $e');
    } finally {
      isLoadingComments.value = false;
    }
  }

  // 刷新评论
  Future<void> refreshComments() async {
    await getComments(isRefresh: true);
  }

  // 格式化时间
  String formatTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '';

    try {
      final dateTime = DateTime.parse(timeStr);
      final now = DateTime.now();
      final difference = now.difference(dateTime);

      if (difference.inDays > 0) {
        return '${difference.inDays}天前';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return timeStr;
    }
  }

  @override
  void onClose() {
    commentController.dispose();
    super.onClose();
  }

  // 提交评论
  Future<void> submitComment() async {
    final content = commentController.text.trim();

    if (content.isEmpty) {
      SmartDialog.showToast('请输入评论内容');
      return;
    }

    if (postId.isEmpty) {
      SmartDialog.showToast('文章ID不能为空');
      return;
    }

    isSubmittingComment.value = true;

    try {
      final request = WriteCommentRequest(
        postId: postId,
        content: content,
      );

      myLog('提交评论请求: ${request.toJson()}');

      final response = await HttpsClient()
          .post(ApiService.writeComments, data: request.toJson());

      if (response == null || response.data == null) {
        SmartDialog.showToast('评论提交失败');
        return;
      }

      final entity = WriteCommentEntity.fromJson(response.data);
      myLog('评论提交响应: ${response.data}');

      if (entity.code == 100 && entity.data == true) {
        SmartDialog.showToast(
          '评论发表成功！',
          alignment: Alignment.center,
        );

        // 清空输入框
        commentController.clear();

        // 刷新评论列表
        await refreshComments();

        myLog('评论提交成功');
      } else {
        SmartDialog.showToast(
          entity.message ?? '评论提交失败',
          alignment: Alignment.center,
        );
      }
    } catch (e, stackTrace) {
      myLog('评论提交失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast('评论提交失败: $e');
    } finally {
      isSubmittingComment.value = false;
    }
  }

  // 删除文章
  Future<void> deletePost() async {
    try {
      // 显示确认对话框
      final result = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('确认删除'),
          content: const Text('确定要删除这篇文章吗？删除后无法恢复。'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text(
                '删除',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ],
        ),
      );

      if (result != true) return;

      if (postId.isEmpty) {
        SmartDialog.showToast('文章ID不能为空');
        return;
      }

      isDeletingPost.value = true;
      SmartDialog.showLoading(msg: "删除中...");

      try {
        final request = DeletePostRequest(id: postId);

        myLog('删除文章请求: ${request.toJson()}');

        final response = await HttpsClient()
            .post(ApiService.deletePost, data: request.toJson());

        if (response == null || response.data == null) {
          SmartDialog.showToast('删除失败，请重试');
          return;
        }

        final entity = DeletePostEntity.fromJson(response.data);
        myLog('删除文章响应: ${response.data}');

        if (entity.code == 100 && entity.data == true) {
          SmartDialog.showToast(
            '文章删除成功！',
            alignment: Alignment.center,
          );

          myLog('文章删除成功');

          // 延迟一下再返回，让用户看到成功提示
          await Future.delayed(const Duration(milliseconds: 1500));

          // 返回上一页
          Get.back();
        } else {
          SmartDialog.showToast(
            entity.message ?? '删除失败',
            alignment: Alignment.center,
          );
        }
      } catch (e, stackTrace) {
        myLog('删除文章失败: $e');
        myLog('堆栈跟踪: $stackTrace');
        SmartDialog.showToast('删除失败: $e');
      } finally {
        SmartDialog.dismiss();
        isDeletingPost.value = false;
      }
    } catch (e) {
      myLog('删除文章对话框错误: $e');
    }
  }

  // 更新文章详情数据
  void updatePostDetail({
    required String title,
    required String content,
    required int state,
  }) {
    if (postDetail.value != null) {
      postDetail.value!.title = title;
      postDetail.value!.content = content;
      postDetail.value!.state = state;

      // 触发更新
      postDetail.refresh();

      myLog('文章详情已更新: $title');
    }
  }

  // 删除评论
  Future<void> deleteComment(int commentId) async {
    try {
      // 显示确认对话框
      final bool? shouldDelete = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('删除评论'),
          content: const Text('确定要删除这条评论吗？'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              style: TextButton.styleFrom(
                foregroundColor: Colors.red,
              ),
              child: const Text('删除'),
            ),
          ],
        ),
      );

      if (shouldDelete != true) {
        return;
      }

      // 添加到删除中的列表
      deletingCommentIds.add(commentId);
      SmartDialog.showLoading(msg: "删除中...");

      try {
        final request = DeleteCommentRequest(
          postId: postId,
          id: commentId,
        );

        myLog('删除评论请求: ${request.toJson()}');

        final response = await HttpsClient()
            .post(ApiService.deleteComments, data: request.toJson());

        if (response == null || response.data == null) {
          SmartDialog.showToast('删除失败，请重试');
          return;
        }

        final entity = DeleteCommentEntity.fromJson(response.data);
        myLog('删除评论响应: ${response.data}');

        if (entity.code == 100 && entity.data == true) {
          SmartDialog.showToast(
            '评论删除成功！',
            alignment: Alignment.center,
          );

          myLog('评论删除成功，ID: $commentId');

          // 从评论列表中移除已删除的评论
          commentList.removeWhere((comment) => comment.id == commentId);

          // 更新评论总数
          if (commentTotalCount.value > 0) {
            commentTotalCount.value = commentTotalCount.value - 1;
          }
        } else {
          SmartDialog.showToast(
            entity.message ?? '删除失败',
            alignment: Alignment.center,
          );
        }
      } catch (e, stackTrace) {
        myLog('删除评论失败: $e');
        myLog('堆栈跟踪: $stackTrace');
        SmartDialog.showToast('删除失败: $e');
      } finally {
        SmartDialog.dismiss();
        deletingCommentIds.remove(commentId);
      }
    } catch (e) {
      myLog('删除评论对话框错误: $e');
    }
  }

  // 检查评论是否正在删除
  bool isCommentDeleting(int commentId) {
    return deletingCommentIds.contains(commentId);
  }
}
